package com.ficv.findme;

import java.util.Date;
import java.util.List;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.StrictMode;
import android.provider.Settings.Secure;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class FindMeService extends Service {
	
	  public static final int NOTIFICATION_ID = 101;
	private final IBinder mBinder = new MyBinder();
	

	
	  @Override
	  public int onStartCommand(Intent intent, int flags, int startId) {

		  
		  Log.v(FindMeService.class.getName(), "service starting");
		  GetNotification.trustSelfSignedSSL();
		  
		  getLocations();
		  getNotifications();

	    return Service.START_NOT_STICKY;
	  }

	  @Override
	  public IBinder onBind(Intent arg0) {
	    return mBinder;
	  }

	  public class MyBinder extends Binder {
		  FindMeService getService() {
	      return FindMeService.this;
	    }
	  }

	  
	  
	  private Date restingTime=new Date();
	  private boolean resting=true;
	  
	  private void getLocations() {
		  
		  
//		  SendPosition sp= new SendPosition(getContentResolver(),getApplicationContext());
//		  sp.execute("37.78","-3.78","50");

		  long delay=0;
		  try {
			  delay=Long.parseLong(JavascriptFacade.DATA);
		  } catch (Throwable t) {
			  Log.v(GpsService.class.getSimpleName(), "Delay forced to 0 " + t.getMessage());
		  }
		  
		  long now= (new Date()).getTime();
			  
		  Log.v(GpsService.class.getSimpleName(), restingTime + "," + resting);
		  Log.v(GpsService.class.getSimpleName(),"getting latency: " + delay);
		  
		  
		  
		  
		  if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER ) && delay>-1) {
			  if(resting && (lastLocation==null || now - restingTime.getTime() > delay)) {
			
			Log.i(FindMeService.class.getName(), "REQUEST UPDATES: ");
		  	resting=false;
		  	restingTime=new Date();
		  	locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
		               1000,          // 15-second interval.
		               10,             // 50 meters.
		               listener);			
			
			  } else if(!resting &&  (now - restingTime.getTime() > 120000)) {
				  Log.v(GpsService.class.getSimpleName(),"pause gps, not getting position");
					locationManager.removeUpdates(listener);
				  	resting=true;
				  	restingTime=new Date();
			  }
		  } else {
			  if(!resting) {
					locationManager.removeUpdates(listener);
				  	resting=true;
				  	restingTime=new Date();				
			  }
			  
			  Log.v(GpsService.class.getSimpleName(),"gps disabled / delay=" + delay);
		  }

	  }
	  
	  
	  private void getNotifications() {
		  Log.i(FindMeService.class.getName(), "REQUEST NOTIFICATION: ");
      	//GetNotification gNot= new GetNotification(getContentResolver());
      	//List<Peticiones> pets=gNot.doInBackground();	
      	try {

      			GetNotification getNot = new GetNotification(getContentResolver());
      			String [] strs = { "37.891", "-4.7997965","50"};
              	List<Contactos> pets=getNot.doInBackground(strs);
              	
//              	SendPosition sp= new SendPosition(getContentResolver(),getApplicationContext());
//
//              	sp.getUrl("testDEviceID", strs);
              		
              	if(pets!=null && pets.size()>0) {
         	    	 notifica2(pets.get(0).getLastMsgId());
         	    	   Intent intent = new Intent("refreshChat");
         	    	  // Add data
         	    	   StringBuffer data=new StringBuffer();
         	    	   for(Contactos c: pets) {
         	    		   if(c.getContactoA().getDeviceId().equalsIgnoreCase(Secure.getString(getContentResolver(), Secure.ANDROID_ID))) {
         	    			  data.append(c.getContactoB().getDeviceId() + "___");
         	    		   } else {
         	    			  data.append(c.getContactoA().getDeviceId() + "___"); 
         	    		   }

         	    	   }
         	    	   
         	    	   intent.putExtra("message", data.toString() );
         	    	  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
              	}
              	Log.i(FindMeService.class.getName(), "mensajes: " + ((pets==null)?"null":pets.size()));
              	
//              	Looper.myLooper().quit();
              	
			 } catch(Throwable t) {
				  Log.e(FindMeService.class.getName(), t.getCause() + ": " + t.getMessage());
			  }
	  }
  
	  private LocationManager locationManager;
	  
	  @Override
	  public void onCreate() {
	    super.onCreate();
	    Log.i(FindMeService.class.getName(), "Service creating");
	    
	    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	    StrictMode.setThreadPolicy(policy); 
	    
	    locationManager =  (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);


	  }
	
	  
	  private final LocationListener listener = new LocationListener() {

		    @Override
		    public void onLocationChanged(Location location) {

		    	//if(isBetterLocation(location, lastLocation)) {
		    		//lastLocation=location;
		    		
			    	try { Log.i(FindMeService.class.getName(), "LOCATION accuracy: " + location.getAccuracy());
			    		
			    		 //if(location.getAccuracy()<20 || intentos++ > 5) {
					    	  
					    	  //setNewPosition(location.getLatitude(),location.getLongitude(),location.getAccuracy());
			    	
								Log.i(FindMeService.class.getName(), "GOT UPDATE: ");
					    	  SendPosition sp= new SendPosition(getContentResolver(),getApplicationContext());
							  sp.execute(String.valueOf(location.getLatitude()),String.valueOf(location.getLongitude()),String.valueOf(location.getAccuracy())); 
							  Log.i(FindMeService.class.getName(), "LOCATION sending: " + location.getLatitude() + "," + location.getLongitude());
					    	  
							  
							  dealWithLocation(location);
			    		 //}
			    	} catch(Throwable e) {
			    		Log.v("ERROR: ", e.getCause() + ": " + e.getMessage());
			       
			    	}
		    	//}
		    }

			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onStatusChanged(String provider, int status,
					Bundle extras) {
				// TODO Auto-generated method stub
				
			}
	  };
	  
	  private void notifica() {
	        
		  String message="mensajes sin leer";
		  Context context = getApplicationContext();
		  
		  int icon = R.drawable.ic_launcher;
	        long when = System.currentTimeMillis();
	        NotificationManager notificationManager = (NotificationManager)
	                context.getSystemService(Context.NOTIFICATION_SERVICE);
	        Notification notification = new Notification(icon, message, when);

	        String title = context.getString(R.string.app_name);

	        Intent notificationIntent = new Intent(context, MainActivity.class);

	        // set intent so it does not start a new activity
	        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
	                Intent.FLAG_ACTIVITY_SINGLE_TOP);
	        PendingIntent intent =
	                PendingIntent.getActivity(context, 0, notificationIntent, 0);
	        notification.setLatestEventInfo(context, title, message, intent);
	        notification.flags |= Notification.FLAG_AUTO_CANCEL;

	        // Play default notification sound
	        notification.defaults |= Notification.DEFAULT_SOUND;

	        // Vibrate if vibrate is enabled
	        notification.defaults |= Notification.DEFAULT_VIBRATE;
	        notificationManager.notify(0, notification);      

	    }
	  
	  private Location lastLocation;
	  
	  private void dealWithLocation(Location location) {
		  long delay=Long.parseLong(JavascriptFacade.DATA);
		  if(location.getAccuracy()<100 && !(delay==0) || delay<0) {
				  lastLocation=location;
					locationManager.removeUpdates(listener);
					restingTime=new Date();
				  	resting=true;
			  }
		}
  
	  public void notifica2(long l) {
		  	
		  try{
		  
			  
				
		  	String ns = Context.NOTIFICATION_SERVICE;
    		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    		
    		int icon = R.drawable.ic_launcher;
    		CharSequence tickerText = "Mensajes en FindMe";
    		long when = System.currentTimeMillis();

    		Notification notification = new Notification(icon, tickerText, when);
    		
    		Context context = getApplicationContext();
    		CharSequence contentTitle = "Mensajes en FindMe";
    		CharSequence contentText="mensajes sin leer";
    		Intent notificationIntent = new Intent(this, MainActivity.class);
	        notificationIntent.putExtra(MainActivity.EXTRA_MESSAGE, l);
    		notificationIntent.putExtra("NotificationMessage", "mensajes sin leer");
    		notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    		notification.flags |= Notification.FLAG_AUTO_CANCEL;

    		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


    		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    			    		

    		mNotificationManager.notify(NOTIFICATION_ID, notification);
    		
    	
		  } catch(Throwable t) {
			  Log.e(FindMeService.class.getName(), t.getCause() + ": " + t.getMessage());
		  }

	}
} 
